<template>
	<view class="">
		<view class="cart-box swiper_box" v-if="cartList.length">
			<u-swipe-action :show="item.show" :index="index" v-for="(item, index) in cartList" :key="item.id"
				@click="deleteItem(item)" @open="open" :options="options" btn-width="120">
				<view class="box" @click.stop="toMallItemlDetail(item)" @changeChecked="changeChecked">
					<view class="box_tag" v-if="item.isGroupBuying == '0'">团购</view>
					<view @click.stop="">
						<u-checkbox v-model="item.checked" shape="circle" icon-size="24rpx" size="40"  active-color="#20B2F9"></u-checkbox>
					</view>
						
					<!-- 商品图片开始 -->
					<view class="center">
						<image :src="item.picUrl" style="border-radius: 20rpx;"></image>
					</view>
					<!-- 商品图片结束 -->
						
					<!-- 商品信息开始 -->
					<view class="right">
						<view class="r-title">
							<text>{{item.commodityName}}</text>
						</view>
						<view class="price-box">
							<view class="price" @click.stop="">
								<view class="content" style="font-size: 34rpx;font-weight: 600;color: #FA3434;">
									<text style="font-size: 26rpx;">¥</text> <text>{{item.isGroupBuying=='1'?item.salesPrice:item.groupBuyPrice}}</text>
								</view>
								<view class="update-count">
									<view class="reduce" @click="minus(item)">
										<u-icon name="minus" size="20" color="#999"></u-icon>
									</view>
									<view class="cart-count">
										<input type="number" v-model="item.number">
									</view>
									<view class="add" @tap="plus(item)">
										<u-icon name="plus" size="20" color="#999"></u-icon>
									</view>
								</view>
							</view>
						</view>
					</view>
					<!-- 商品信息结束 -->
				</view>
			</u-swipe-action>
		</view>
		<view class="empty_box" v-else>
			<image src="../../static/empty_cart.png" mode=""></image>
			<view class="toGoodsBtn" @click="toHome()">去逛逛</view>
		</view>
		<view class="balance" v-if="cartList.length">
			<view class="left">
				<u-checkbox v-model="allChcked" shape="circle" icon-size="24rpx" size="40" active-color="#20B2F9"></u-checkbox>
				<view style="text-align: center;">全选</view>
			</view>
			<view class="right">
				<text class="totalPrice">合计：</text>
				<view>
					<text style="font-weight: 600;">￥</text> <text class="numberPrice">{{totalPrice}}</text>
				</view>
				<view class="toGoodsBtn" size="mini" @click="toOrder" :disabled="!total">去支付</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	import {
		cartItem
	} from '../../components/cartItem.vue'
	import {
		goodItem
	} from '../../components/goodItem.vue'
	import {
		getCartListApi,
		editCartListApi
	} from '../../common/API/cartApi.js'
	import {
		delGoodApi,
		getOrderListApi,
		getGoodsListApi
	} from '../../common/API/goodsApi.js'
	import {
		filterGoods
	} from '../../utils/filter.js'
	export default {
		components: {
			cartItem,
			goodItem
		},
		data() {
			return {
				goodsTotal: 0,
				pageNum: 1,
				GoodsList: [],
				cartList: [],
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#dd524d',
						heigth: '100rpx',
						width: '80rpx'
					}
				}],
			};
		},
		computed: {
			...mapState('user', ['ylEnterprise']),
			allChcked: {
				get() {
					let status = false
					status = this.cartList?.every(item => item.checked)
					if (!this.cartList.length) {
						status = false
					}
					return status
				},
				set(e) {
					this.cartList?.forEach(item => e ? item.checked = 1 : item.checked = 0)
					return e
				}
			},
			total: function() {
				let sum = 0
				this.cartList?.forEach(item => {
					if (item.checked) {
						sum = sum + item.number
					}
				})
				return sum
			},
			totalPrice: function() {
				let sum = 0
				this.cartList?.forEach(item => {
					if (item.checked) {
						sum = sum + item.number * (item.isGroupBuying == '0' ? item.groupBuyPrice : item
							.salesPrice)
					}
				})
				return sum.toFixed(2)
			},
			showTitle() {
				return this.cartList.some(item => item.checked)
			},
			checkedArr() {
				const newArr = this.cartList.filter(item => item.checked)
				return newArr
			},
			checkedresult() {
				const result = this.checkedArr.every(item => item.inventory >= item.number)
				return result
			}
		},
		methods: {
			plus(item) {
				item.number = Number(item.number) + 1
			},
			minus(item) {
				// console.log('点减号了--------')
				if (item.number == 1) {
					// console.log('父组件商品减到0-----')
					uni.showModal({
						content: '确认删除此商品',
						confirmColor: "#F18F36",
						confirmText: '删除',
						success: async (res) => {
							if (res.confirm) {
								const res1 = await delGoodApi(item.id)
								if (res1.status == 200) {
									uni.$showMsg('删除成功')
									this.getCartList()
								} else {
									uni.$showMsg(res1.message)
								}
							}
						}
					})
				} else {
					item.number = Number(item.number) - 1
				}
			},
			deleteItem(item){
				uni.showModal({
					content: '确认删除此商品',
					confirmColor: "#F18F36",
					confirmText: '删除',
					success: async (res) => {
						if (res.confirm) {
							const res1 = await delGoodApi(item.id)
							if (res1.status == 200) {
								uni.$showMsg('删除成功')
								this.getCartList()
							} else {
								uni.$showMsg(res1.message)
							}
						}
					}
				})
			},
			open(index) {
				// 先将正在被操作的swipeAction标记为打开状态，否则由于props的特性限制，
				// 原本为'false'，再次设置为'false'会无效
				this.cartList[index].show = true;
				this.cartList.map((val, idx) => {
					if (index != idx) {
						this.cartList[idx].show = false;
					}
				})
			},
			async getCartList() {
				const res = await getCartListApi(this.ylEnterprise.enterpriseCode)
				if (res.status === 200) {
					console.log('购物车商品',JSON.stringify(res.data))
					this.cartList = res.data || []
					let tempList = res.data || []
					if (tempList.length > 0) {
						console.log('购物车商品数', JSON.stringify(tempList.length))
						uni.setTabBarBadge({
							index: 2,
							text: tempList.length.toString()
						})
					} else {
						// console.log('购物车没数据了')
						uni.removeTabBarBadge({
							index: 2
						})
					}
				}

			},
			async getGoodsList() {
				if (this.throttle) return uni.$showMsg('数据请求中')
				this.throttle = true
				const res = await getGoodsListApi({
					pageNum: this.pageNum,
					pageSize: 5,
					//销售类型0-批发1-零售
					salesType: '1',
					enterpriseCode: this.ylEnterprise.enterpriseCode
				})
				this.throttle = false
				if (res.status === 200) {
					this.GoodsList.push(...res.data.records)
					this.goodsTotal = res.data.total
				} else {
					uni.$showMsg(res.message)
				}
			},
			async PurchaseList(e) {
				this.cartList.forEach(item => {

					if (item.id === e.id) {
						item.number = e.number
						if (e.number == 0) {
							console.log('父组件商品减到0')
							uni.showModal({
								content: '确认删除此商品',
								confirmColor: "#0091D7",
								success: async (res) => {
									if (res.confirm) {
										const res1 = await delGoodApi(item.id)
										if (res1.status == 200) {
											uni.$showMsg('删除成功')
											this.getCartList()
										} else {
											uni.$showMsg(res1.message)
										}
									} else {
										item.number = 1

									}
								}
							})
						}
					}

				})
				// this.cartList.forEach(item => {
				// 	if (item.id === e.id) {
				// 		item.number = e.number
				// 	}
				// })
			},
			changeChecked(e) {
				this.cartList.forEach(item => {
					if (item.id === e.id) {
						item.inventory < item.number ? uni.$showMsg('商品数量超出库存') : ''
						item.checked = e.checked
					}
				})
			},
			toOrder() {
				// if (!this.checkedresult) return uni.$showMsg('有商品数量超出库存')
				if(!this.checkedArr.length) return uni.$showMsg('您还没有选择商品哦')
				let str = this.checkedArr[0].commodityCode
				// let shopCode = this.checkedArr[0].enterpriseCode
				// let isGroupBuying = this.checkedArr[0].isGroupBuying
				// let throttle = false
				// let isGoodsCate = false
				let tempItme = {}
				this.checkedArr.forEach((item, index) => {
					console.log('购物车中勾选的',item)
					if(item.numberOfPackages!=null){
						console.log('存在只能单独结算')
						tempItme = item
					}
				// 	if (item.enterpriseCode !== shopCode) {
				// 		throttle = true
				// 	}
				// 	if (item.isGroupBuying !== isGroupBuying) {
				// 		isGoodsCate = true
				// 	}
					if (index > 0) {
						str = str + '/' + item.commodityCode
					}
				})
				if (this.checkedArr.length > 1 && tempItme){
					return uni.$showMsg('【' + tempItme.commodityName + '】只能单独结算')
				}

				// if (throttle) {
				// 	return uni.$showMsg('下单门店不同,请分开下单')
				// 	// 
				// }
				// if (isGoodsCate) {
				// 	return uni.$showMsg('商品类型不同,请分开下单')
				// }
				console.log('str',str)
				wx.navigateTo({
					url: `/subPackages/order/order?goodsIds=${str}`
				})
			},
			delGood() {
				this.cartList.forEach(async item => {
					if (item.checked) {
						const res = await delGoodApi(item.id)
						if (res.status === 200) {
							uni.$showMsg('删除成功')
							this.getCartList()
						} else {
							uni.$showMsg(res.message)
						}
					}
				})
			},
			toHome() {
				uni.switchTab({
					url: "/pages/sort/sort"
				})
			},
			toMallItemlDetail(item){
				uni.navigateTo({
					url: `/subPackages/mallItemDetial/mallItemDetial?code=${item.uniqueId}&enterpriseCode=${item.enterpriseCode}`
				})
			},
		},
		onLoad() {
			// this.getGoodsList()
		},
		onShow() {
			if(uni.getStorageSync('ylToken')){
				this.getCartList()
			}else{
				uni.showModal({
					content:"还未登录，请先登录",
					success(res) {
						if(res.confirm){
							uni.navigateTo({
								url:'/subPackages/login/login'
							})
						}
					},
				})
			}
		},
		onReachBottom() {
			if (this.goodsTotal <= this.GoodsList.length) return uni.$showMsg('已经到底啦')
			this.pageNum = this.pageNum + 1
			this.getGoodsList()
		},
		async onHide() {
			const newArr = []
			this.cartList?.forEach(item => {
				newArr.push({
					checked: item.checked,
					number: item.number,
					uniqueId: item.commodityCode
				})
			})
			if (newArr.length) {
				const res = await editCartListApi(newArr)
			}
		}
	}
</script>
<style>
	page{
		background: #f8f8f8;
	}
</style>
<style lang="scss" scoped>
	.swiper_box {
		// height: 100%;
		overflow: auto;
		margin-bottom: 200rpx;
		border-radius: 16rpx;
		width: 100%;
		// margin: 0 32rpx;
		padding: 30rpx 0rpx 30rpx 10rpx;
		padding-top: 0;
		.swipe-action__content{
			// width: 96%;
			background: #fff;
			padding: 24rpx;
		}
		/deep/.u-swipe-action {
			margin: 24rpx auto;
			// border-bottom: 1rpx solid #F2F2F2;
			.u-swipe-view{
				// width: 840rpx !important;
			}
			.u-swipe-action-item {
				.u-swipe-action-item__right {
					right: 10rpx;
	
					.u-swipe-action-item__right__button__wrapper {
						border-radius: 16rpx !important;
					}
				}
	
				.u-swipe-action-item__content {
					padding: 20rpx 0;
				}
			}
	
			.u-border-bottom {
				border: none;
			}
		}
	}
	.page {
		padding: 0 32rpx;
	}

	.title {
		display: flex;
		padding: 20rpx;
		justify-content: space-between;
	}

	.cart-box {
		margin-top: 16rpx;
		margin-bottom: 32rpx;
	}

	.empty_box {
		padding-top: 45%;
		display: flex;
		flex-direction: column;
		align-items: center;

		image {
			width: 330rpx;
			height: 275rpx;
			padding-bottom: 32rpx;
		}

		text {
			margin-bottom: 48rpx;
		}
	}

	.recommend {
		text-align: center;
		color: #333333;
		font-weight: 500;
		font-size: 34rpx;
		margin-bottom: 32rpx;
	}

	.goods-box {
		padding-bottom: 112rpx;
	}

	.balance {
		display: flex;
		justify-content: space-between;
		align-items: center;
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 112rpx;
		background-color: #fff;
		padding: 10rpx 20rpx;
		box-sizing: border-box;

		.left {
			display: flex;
			align-items: center;

			/deep/ .u-checkbox {
				display: block;
				margin-right: 16rpx
			}
		}

		.right {
			display: flex;
			align-items: center;
			justify-content: center;
			color: #FA5151;

			.totalPrice {
				font-size: 24rpx;
				font-weight: 400;
				color: #333;
			}

			.numberPrice {
				font-weight: 600;
				font-size: 38rpx;
				margin-right: 16rpx;
			}

			.account {
				width: 240rpx;
				height: 80rpx;
				border-radius: 40rpx;
				// font-size: 34rpx;
				font-weight: 600;
				text-align: center;
				line-height: 80rpx;
				background-color: #20B2F9 ;
				// color: #333333;
			}

			.comfirm-btn {
				margin: 0;
			}
		}
	}

	.toGoodsBtn {
		color: #fff;
		border-radius: 20rpx;
		background: linear-gradient(90deg, #20B2F9 0.31%, #009BE5 101.68%);
		width: 240rpx;
		height: 80rpx;
		text-align: center;
		line-height: 80rpx;
		font-weight: 700;
	}

	.box {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 224rpx;
		// margin: 24rpx 32rpx;
		background-color: #fff;
		padding: 32rpx 24rpx;
		border-radius: 10rpx;
		position: relative;
		padding-right: 32rpx;
		.box_tag {
			position: absolute;
			top: 0;
			left: 0;
			width: 120rpx;
			height: 44rpx;
			text-align: center;
			background: url('../../static/cart_tag.png');
			background-size: 120rpx 44rpx;
			color: #fff;
			font-size: 24rpx;
		}

		.left {}

		.center {
			height: 160rpx;
			width: 160rpx;
			margin-right: 16rpx;

			image {
				width: 100%;
				height: 100%;
			}
		}

		.right {
			height: 100%;
			display: flex;
			flex: 7;
			flex-direction: column;
			justify-content: space-between;

			.r-title {
				display: flex;
				justify-content: space-between;
				padding-right: 20rpx;
			}

			.attr {
				font-size: 24rpx;
				padding: 4rpx;
				background-color: #ccc;
				display: inline-block;
			}

			.price-box {
				display: flex;
				flex-direction: column;
				justify-content: center;

				text {
					font-size: 20rpx;
					margin-bottom: 2rpx;
				}

				.price {
					display: flex;
					justify-content: space-between;
					align-items: center;

					.content {
						// font-size: 24rpx;
						margin-top: 40rpx;
						text {
							font-size: 34rpx
						}
					}
				}
			}

		}
	}

	// 加减数量
	.update-count {
		margin-top: 40rpx;
		display: flex;

		.reduce {
			width: 50rpx;
			height: 50rpx;
			color: #979797;
			display: flex;
			justify-content: center;
			border: 1px solid #E5E5E5;
		}

		.add {
			width: 50rpx;
			height: 50rpx;
			color: #979797;
			display: flex;
			justify-content: center;
			border: 1px solid #E5E5E5;
		}

		.cart-count {
			width: 72rpx;
			height: 50rpx;
			color: #666;
			text-align: center;
			display: flex;
			justify-content: center;
			align-items: center;
			border-top: 1px solid #E5E5E5;
			border-bottom: 1px solid #E5E5E5;
		}
	}
	/deep/ .u-checkbox__icon-wrap--checked .u-icon__icon{
		color: #fff !important;
	}
</style>